package com.samsung.sbackup;

import java.io.File;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;

public class FragmentSettingsPreference extends PreferenceFragment implements
		OnSharedPreferenceChangeListener {

	public static final String BACKUP_PATH = "pref_backup_path";
	public static final String MAX_BACKUPS = "pref_max_backups";
	public static final String SCHEDULE_BACKUP = "pref_schedule_backup";
	public static final String REPEATATION = "pref_backup_repeatation";
	public static final String BACKUP_TIME = "pref_backup_time";
	public static final String BACKUP_OPTIONS = "pref_backup_options";

	ListPreference prefBackupPath;
	Preference prefScheduleBackup;
	ListPreference prefMaxBackups;
	CheckBoxPreference prefRemindBackup;

	SharedPreferences sharedPref;
	SharedPreferences.Editor prefEditor;

	//
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preference);
		sharedPref = PreferenceManager
				.getDefaultSharedPreferences(getActivity()
						.getApplicationContext());
		prefEditor = sharedPref.edit();

		// initiate preferences
		initPrefMaxBackups();
		initPrefBackupPath();
		initPrefScheduleBackup();
	}

	/**
	 * init backup path preference
	 */
	private void initPrefMaxBackups() {
		prefMaxBackups = (ListPreference) findPreference(MAX_BACKUPS);
		prefMaxBackups.setSummary(prefMaxBackups.getValue());
	}

	/**
	 * init schedule backup preference
	 */
	public void initPrefScheduleBackup() {
		prefScheduleBackup = findPreference(SCHEDULE_BACKUP);
		boolean scheduleBackupState = sharedPref.getBoolean(SCHEDULE_BACKUP,
				false);
		if (scheduleBackupState)
			prefScheduleBackup.setSummary("Enabled");
		else
			prefScheduleBackup.setSummary("Disabled");
		prefScheduleBackup
				.setOnPreferenceClickListener(new OnPreferenceClickListener() {

					@Override
					public boolean onPreferenceClick(Preference preference) {
						Intent i = new Intent(getActivity()
								.getApplicationContext(),
								ScheduleSettings.class);
						startActivity(i);
						return false;
					}
				});
	}

	/**
	 * init backup path preference
	 */
	private void initPrefBackupPath() {
		String[] storage = getStorageDirectories();
		String internalPath = "";
		String externalPath = "";
		if (storage[0] != null || storage[1] != null) {
			externalPath = String.valueOf(storage[0]);
			internalPath = String.valueOf(storage[1]);
		} else {
			externalPath = "Not available";
			internalPath = "Not available";
		}

		String[] pathEntries;
		String[] pathValues;

		if (new File(externalPath).list() != null) {
			pathEntries = new String[] { "External Storage", "Internal Storage" };
			pathValues = new String[] {
					externalPath + "/Android/data/"
							+ getActivity().getPackageName()
							+ "/files/Download",
					internalPath + "/Android/data/"
							+ getActivity().getPackageName()
							+ "/files/Download" };
		} else {
			pathEntries = new String[] { "Internal Storage" };
			pathValues = new String[] { internalPath + "/Android/data/"
					+ getActivity().getPackageName() + "/files/Download" };
		}
		prefBackupPath = (ListPreference) findPreference(BACKUP_PATH);
		if (prefBackupPath == null) {
			System.out.println("null pref");
		} else if (prefBackupPath.getValue() == null) {
			prefBackupPath.setEntries(pathEntries);
			prefBackupPath.setEntryValues(pathValues);
			prefBackupPath.setValueIndex(0);
			prefBackupPath.setSummary(pathValues[0]);
		} else {
			prefBackupPath.setEntries(pathEntries);
			prefBackupPath.setEntryValues(pathValues);
			prefBackupPath.setSummary(prefBackupPath.getValue());
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		// Set up a listener whenever a key changes
		sharedPref.registerOnSharedPreferenceChangeListener(this);
		initPrefScheduleBackup();
	}

	@Override
	public void onPause() {
		super.onPause();
		// Unregister the listener whenever a key changes
		sharedPref.unregisterOnSharedPreferenceChangeListener(this);
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		if (key.equals(BACKUP_PATH)) {
			prefBackupPath.setSummary(sharedPreferences.getString(key, ""));
			MainActivity.createFolder(sharedPreferences.getString(key, "/"),
					getActivity());
		}
		if (key.equals(MAX_BACKUPS)) {
			prefMaxBackups.setSummary(sharedPreferences.getString(key, ""));
		}
	}

	/**
	 * @return paths to external storage[0] and internal storage[1]
	 */
	public static String[] getStorageDirectories() {

		String[] storages = new String[2];
		File f = new File("/storage");
		File[] files = f.listFiles();
		if (files != null) {
			for (int i = 0; i < files.length; i++) {

				if (files[i].getName().contains("ext")
						|| files[i].getName().contains("sdcard1")) {
					// make external storage be path[0]
					storages[0] = "/storage" + "/" + files[i].getName();
				} else if (files[i].getName().contains("sdcard0"))
					storages[1] = "/storage" + "/" + files[i].getName();
			}
		}
		return storages;
	}
}